#include "QReadJson.h"
#include <QDebug>
#include <QApplication>
#include <QDir>
QReadJson * QReadJson::instance = nullptr;



QReadJson::QReadJson()
{

}



QReadJson *QReadJson::GetInstance()
{
    if(nullptr == instance)
    {
        instance = new QReadJson();
    }
    return instance;
}

QString QReadJson::readFile(QString filePath, QString fileName)
{
    bool result;
    QString errorString,retStr;
    if(fileName.isEmpty()){
        retStr = jsonFileToStr(&result,&errorString,filePath + "/" + fileName);
    }else {
        retStr = jsonFileToStr(&result,&errorString,filePath);
    }

    if(result){
        return retStr;
    }else {
        return errorString;
    }

}

bool QReadJson::writeFile(QString filePath,QString &data,QString fileName)
{
    QString errorString;
    bool ret ;
    if(fileName.isEmpty()){
        ret = strToJsonFile(&errorString,filePath + "/" +fileName,data);
    }else {
        ret = strToJsonFile(&errorString,filePath,data);
    }

    if(!ret){
        qDebug()<<__FUNCTION__<<"Write Data failed!"<<errorString;
    }
    return  ret;
}


bool QReadJson::strToJsonFile(QString *errorString,const QString &filePath, const QString &data) {
    QFile file(filePath);
    if (file.open(QFile::WriteOnly)) {
        auto json = QJsonDocument::fromJson(data.toUtf8());
        auto data  = json.toJson();

        file.write(data);
        file.close();
        errorString->clear();
        return true;
    } else {
        *errorString = "FileName: " + file.fileName() + " Error: " + file.errorString();
        return false;
    }
}

QString QReadJson::debug()
{
    qDebug()<<"666";
    return  "dsdsdsdsds";
}

QString QReadJson::jsonFileToStr(bool *result,QString *errorString,const QString &filePath) {
    QString ret;
    QFile file(filePath);
    if (file.open(QFile::ReadOnly)) {
        auto bytes = file.readAll();
        auto json = QJsonDocument::fromJson(bytes);
        ret = QString(json.toJson());

        file.close();
        errorString->clear();
        *result = true;
    } else {
        ret.clear();
        *result = false;
        *errorString = "FileName: " + file.fileName() + " Error: " + file.errorString();
    }
    return ret;
}

